#include "FBO.h"
#include <iostream>
using namespace std;

FBO::FBO()
{
	glGenFramebuffers(1, &mFbo);
}

void FBO::AttachColorBuffer(const char * bufferName, GLenum attachment, GLenum dataType, int width, int height)
{
	GLuint colorBuffer;
	glBindFramebuffer(GL_FRAMEBUFFER, mFbo);
	glGenTextures(1, &colorBuffer);
	glBindTexture(GL_TEXTURE_2D, colorBuffer);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, dataType, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
	glBindTexture(GL_TEXTURE_2D, 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, colorBuffer, 0);

	mDrawBuffers.push(attachment);
	mBuffers.insert(make_pair(bufferName, colorBuffer));

	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

void FBO::AttachDepthBuffer(const char * bufferName, int width, int height)
{
	GLuint depthMap;
	glBindFramebuffer(GL_FRAMEBUFFER, mFbo);
	glGenTextures(1, &depthMap);
	glBindTexture(GL_TEXTURE_2D, depthMap);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
	glBindTexture(GL_TEXTURE_2D, 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
	mBuffers.insert(make_pair(bufferName, depthMap));
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

GLuint FBO::GetBuffer(const char * bufferName)
{
	auto iter = mBuffers.find(bufferName);
	if (iter == mBuffers.end())
	{
		return 0;
	}
	return iter->second;
}

void FBO::Finish()
{
	do
	{
		int nCount = (int)mDrawBuffers.size();
		if (nCount <= 0)
		{
			break;
		}

		GLenum * buffers = new GLenum[nCount];
		int i = 0;
		while (!mDrawBuffers.empty())
		{
			buffers[i++] = mDrawBuffers.top();
			mDrawBuffers.pop();
		}

		glBindFramebuffer(GL_FRAMEBUFFER, mFbo);
		glDrawBuffers(nCount, buffers);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
	} while (0);
}

void FBO::Bind()
{
	glBindFramebuffer(GL_FRAMEBUFFER, mFbo);
}

void FBO::Unbind()
{
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
